//公共js	
var ERROR_ICON = "<i class='fa fa-times-circle'></i> ";
var SPLIT_CODE = "@@HZFI@@";

(function($) {
	
	//关闭ibox
	$(document).on('click', '.close-link', function(){
		var content = $(this).closest('div.ibox');
	    content.remove();
	});
	
	layer.config({
	  skin: 'layer2-class'
	});
	
	$(document).on('click', '.cancle-btn', function(){
		closeWin();
	});
	
	//折叠ibox
	$(document).on('click','.collapse-link',function () {
	    var ibox = $(this).closest('div.ibox');
	    var button = $(this).find('i');
	    var content = ibox.find('div.ibox-content');
	    content.slideToggle(200);
	    button.toggleClass('fa-chevron-up').toggleClass('fa-chevron-down');
	    ibox.toggleClass('').toggleClass('border-bottom');
	    setTimeout(function () {
	        ibox.resize();
	        ibox.find('[id^=map-]').resize();
	    }, 50);
	});
	
	//构造下拉框
	$.fn.ajaxSelect = function(options){
		var defaults = {    
			    defaultValue: null,
			    hasNull:false,
			    onSuccess:null,
			    data:null,
			    removeValue:null,
			    formatter:null,
			    async:true,
			    root:null
		}; 
		var opts = $.extend(defaults, options); 
		var select = $(this);
		if(opts.hasNull==true){
			$("<option value=''></option>").appendTo(select);
		}
		var reValues = new Array(); 
		if(opts.removeValue){
			var ss = opts.removeValue.split(",");
			for(var index=0;index<ss.length;index++){
				reValues.push(ss[index]);
			}
		}
		
		if(opts.data){
			var json = opts.data;
			$.each(json,function(index){
				
				if(arrayHasValue(reValues,this[opts.valueName])){
					return true;
				}
				
				var opt = null;
				if(this[opts.valueName]==opts.defaultValue){
					opt = $("<option value='"+this[opts.valueName]+"' selected>"+this[opts.textName]+"</option>");
				}else{
					opt = $("<option value='"+this[opts.valueName]+"'>"+this[opts.textName]+"</option>");
				}
				opt.appendTo(select);
				if(opts.formatter){
					opts.formatter(this,opt);
				}
			});
			bindICheck();
			if(opts.onSuccess!=null){
				opts.onSuccess(json);
			}
		}else{
			$.ajax({
				   type: "POST",
				   url: opts.url,
				   data: opts.param,
				   async:opts.async,
				   success: function(data){
						if(data){
							//var json = $.parseJSON(data);
							var json = eval(data);
							if(opts.root){
								var keys = opts.root.split(".");
								var temp_val = null;
								for(var index=0;index<keys.length;index++){
									temp_val = json[keys[index]];
								}
								json = temp_val;
							}
							$.each(json,function(index){
								
								if(arrayHasValue(reValues,this[opts.valueName])){
									return true;
								}
								
								var opt = null;
								if(this[opts.valueName]==opts.defaultValue){
									opt = $("<option value='"+this[opts.valueName]+"' selected='selected' >"+this[opts.textName]+"</option>");
								}else{
									opt = $("<option value='"+this[opts.valueName]+"'>"+this[opts.textName]+"</option>");
								}
								opt.appendTo(select);
								if(opts.formatter){
									opts.formatter(this,opt);
								}
							});
							bindICheck();
							if(opts.onSuccess!=null){
								opts.onSuccess(json);
							}
						}
				   }
				});
		}
		return $(this);
		
	}
	//构造单选或者复选框
	$.fn.ajaxInput = function(options) {
		var defaults = {
			defaultValue : null,
			onClick : null,
			onChange : null,
			classType : "rowClass",
			rowSize : 10,
			removeValue : null,
			data : null,
			formatter : null,
			splitDefaultValue : true,
			onSuccess : null,
			async : true,
			root : null
		};
		var opts = $.extend(defaults, options);
		var select = $(this);
		var defs = new Array();
		if (opts.defaultValue) {
			if (opts.splitDefaultValue == true) {
				var ss = opts.defaultValue.split(",");
				for (var index = 0; index < ss.length; index++) {
					defs.push(ss[index]);
				}
			} else {
				defs.push(opts.defaultValue);
			}
		}
		var reValues = new Array();
		if (opts.removeValue) {
			var ss = opts.removeValue.split(",");
			for (var index = 0; index < ss.length; index++) {
				reValues.push(ss[index]);
			}
		}
		var opt_index = 0;
		if (opts.data) {
			createInputHtml(opts.data, opts, reValues, defs, select);
			bindICheck();
			if (opts.onSuccess) {
				opts.onSuccess(opts.data);
			}
		} else {
			$.ajax({
				type : "POST",
				url : opts.url,
				data : opts.param,
				async : opts.async,
				success : function(data) {
					if (data) {
						//var json = $.parseJSON(data);
						var json = eval(data);
						if (opts.root) {
							var keys = opts.root.split(".");
							var temp_val = null;
							for (var index = 0; index < keys.length; index++) {
								temp_val = json[keys[index]];
							}
							json = temp_val;
						}
						createInputHtml(json, opts, reValues, defs, select);
						bindICheck();
						if (opts.onSuccess) {
							opts.onSuccess(json);
						}
					}
				}
			});
		}
		return $(this);
	}
	
	$.fn.myReset = function(){
		$(this)[0].reset();
		$(this).find('div').each(function(index){
			if($(this).hasClass('icheckbox_square-green') || $(this).hasClass('radioClass')){
				$(this).removeClass('checked');
			}
		});
	}
	
})(jQuery);

function createInputHtml(data, opts, reValues, defs, select) {
	var opt_index = 0;
	$.each(
		data,
		function(index) {
			var opt = null;
			if (arrayHasValue(reValues, this[opts.valueName])) {
				return true;
			}
			opt_index++;
			if (arrayHasValue(defs, this[opts.valueName])) {
				if('colClass' == opts.classType){  //内联样式
					if ('radio' == opts.type) {
						opt = $('<div class="radio i-checks"><label><input type="radio" name="'+opts.name+'" value="'+this[opts.valueName]+'" checked="checked">'+this[opts.textName]+'</label></div>');
					} else if ('checkbox' == opts.type) {
						opt = $('<div class="checkbox i-checks"><label><input type="checkbox" name="'+opts.name+'" value="'+this[opts.valueName]+'" checked="checked">'+this[opts.textName]+'</label></div>');
					}
				} else {
					if ('radio' == opts.type) {
						opt = $('<label class="radio-inline i-checks"><input type="radio" name="'+opts.name+'" value="'+this[opts.valueName]+'" checked="checked">'+this[opts.textName]+'</label>');
					} else if ('checkbox' == opts.type) {
						opt = $('<label class="checkbox-inline i-checks"><input type="checkbox" name="'+opts.name+'" value="'+this[opts.valueName]+'" checked="checked">'+this[opts.textName]+'</label>');
					}
				}
			} else {
				if('colClass' == opts.classType){  //内联样式
					if ('radio' == opts.type) {
						opt = $('<div class="radio i-checks"><label><input type="radio" name="'+opts.name+'" value="'+this[opts.valueName]+'">'+this[opts.textName]+'</label></div>');
					} else if ('checkbox' == opts.type) {
						opt = $('<div class="checkbox i-checks"><label><input type="checkbox" name="'+opts.name+'" value="'+this[opts.valueName]+'">'+this[opts.textName]+'</label></div>');
					}
				} else {
					if ('radio' == opts.type) {
						opt = $('<label class="radio-inline i-checks"><input type="radio" name="'+opts.name+'" value="'+this[opts.valueName]+'">'+this[opts.textName]+'</label>');
					} else if ('checkbox' == opts.type) {
						opt = $('<label class="checkbox-inline i-checks"><input type="checkbox" name="'+opts.name+'" value="'+this[opts.valueName]+'">'+this[opts.textName]+'</label>');
					}
				}
			}

			opt.appendTo(select);

			if (opts.formatter) {
				opts.formatter(this, opt);
			}

			if (opt_index % opts.rowSize == 0) {
				$("<br/>").appendTo(select);
			}
			if (opts.onClick) {
				opt.click(function() {
					opts.onClick(this);
				});
			}
			if (opts.onChange) {
				opt.change(function() {
					opts.onChange(this);
				});
			}
		});
}

/**
 * 刷新页面
 */
function refreshPage() {
	window.location.reload();
}

/**
 * 获取URL参数值
 * 
 * @param name
 * @returns
 */
function getURLParamValue(name) {
	var url = window.location.href;
	var index = url.indexOf("?");
	if (index < 0) {
		return null;
	}
	var params = url.substring(index + 1).split("&");
	for (var i = 0; i < params.length; i++) {
		var ss = params[i].split("=");
		if (ss[0] == name && ss.length > 1) {
			return ss[1];
		}
	}
	return null;
}

/**
 * 根据日子字符串的格式，比较两个日期 字符串的格式例如 "2005-10-10" "2005-10-10 22:10" "2003-4-10
 * 10:34:34" 如果第一个字符串小于第二个字符串，返回true 如果相等，返回0 大于返回false
 */
function compareDate(dateStr1, dateStr2) {
	var minus = parseDate(dateStr1) - parseDate(dateStr2);
	if (minus > 0) {
		return false;
	} else if (minus < 0) {
		return true;
	}
	return true;
}

/**
 * 如果是name相同的话以逗号分隔
 */
$.fn.serializeObject = function() {
	var o = {};
	$.each(this.serializeArray(), function(index) {
		if (!(this['value'] == null || this['value'] == "")) {
			if (o[this['name']]) {
				o[this['name']] = o[this['name']] + "," + this['value'];
			} else {
				o[this['name']] = this['value'];
			}
		}
	});
	return o;
};

/**
 * 将form表单元素的值序列化成字符串，如：name=value&name=value&name=value&...
 * 
 * @param formId
 *            要序列化的表单的id
 * @param encode
 *            是否需要编码
 * @returns {String}
 */
function serializeString(formId, encode) {
	var result = '';
	var $fields = $('#' + formId).serializeArray();
	var len = $fields.length;
	$.each($fields, function(i, field) {
		if (!(field.value == null || field.value == "")) {
			var value = '';
			if (encode) {
				value = encodeURIComponent(field.value);
				value = replaceHtml(value);
			} else {
				value = field.value
				value = replaceHtml(value);
			}
			result += field.name + "=" + value;
			if (i != len - 1) {
				result += '&';
			}
		}
	});
	return result;
}

function getFormJson(formId, isString) {
	var o = {};
	var form = $("#" + formId);
	$(form).find('input,textarea,select').each(function() {
		var key = $(this).attr('name');
		if (key) {
			if ($(this).val() != null && $(this).val() != "") {
				if ($(this).attr('type') == 'radio') {
					if ($(this).is(":checked")) {
						o[key] = $(this).val();
					}
				} else if ($(this).attr('type') == 'checkbox') {
					if (!isString) {
						if ($(this).is(':checked')) {
							if (o[key]) {
								if (!o[key].push) {
									o[key] = [ o[key] ];
								}
								o[key].push($(this).val() || '');
							} else {
								// 即使一个值也应该是数组
								o[key] = new Array();
								o[key].push($(this).val() || '');
							}
						}
					} else {
						if ($(this).is(':checked')) {
							if (o[key]) {
								o[key] = o[key] + "," + $(this).val() || '';
							} else {
								o[key] = $(this).val() || '';
							}
						}
					}
				} else {
					o[key] = $(this).val();
				}
			}

		}
	});
	return o;
}

function getSearchFormJson(formId, isString) {
	var o = {
		"obj" : ""
	};
	o.obj = getFormJson(formId, isString);
	return o;
}

/**
 * 数组array是否含有值value
 * 
 * @param array
 * @param value
 * @returns {Boolean}
 */
function arrayHasValue(array, value) {
	for (var index = 0; index < array.length; index++) {
		if (array[index] == value) {
			return true;
		}
	}
	return false;
}

function bindICheck(){
	$('.i-checks').iCheck({
        checkboxClass: 'icheckbox_square-green',
        radioClass: 'iradio_square-green',
    });
}

function alertMsg(msg,type){
	parent.layer.alert(msg,{icon:type});
}

function closeWin(){
	 parent.layer.close(parent.layer.getFrameIndex(window.name));
}

/**
 * 将以link连接的字符串中指定串替换为所需串
 * @param org 需要被处理的字符串
 * @param des 需要被替换的字符串
 * @param des2 替换成的字符串
 * @param link 链接字符串
 * @returns {String}
 */
function replaceString(org,des,des2,link){
	var ret = '';
	if(org && ''!=org){
		var args = org.split(link);
		for(var i=0;i<args.length;i++){
			if(des == args[i]){
				if('' != des2){
					if('' == ret){
						ret = des2;
					} else {
						ret += link + des2;
					}
				}
			} else {
				if('' == ret){
					ret = args[i];
				} else {
					ret += link + args[i];
				}	
			}
		}
	}
	return ret;
}

/**
 * 刷新页面
 */
function refreshPage(){
	window.location.reload();
}

/**
 * 获取当前iframe对应的菜单URL
 * @returns
 */
function getIframeMenuURL(){
	var name = window.name;
	var frame_ = $(window.parent.document).find("iframe[name="+name+"]").eq(0);
	var dataid = frame_.attr("data-id");
	if(dataid){
		return dataid;
	}
	return null;
}

/**
 * 设置当前iframe 的 src
 * @param url
 */
function setIframeMenuURL(url){
	var name = window.name;
	var frame_ = $(window.parent.document).find("iframe[name="+name+"]").eq(0);
	frame_.attr("src",url);
}

/**
 * 获取URL参数值
 * @param name
 * @returns
 */
function getURLParamValue(name){
	var url = window.location.href;
	var index = url.indexOf("?");
	if(index<0){
		return null;
	}
	var params =  url.substring(index+1).split("&");
	for(var i=0;i<params.length;i++){
		var ss = params[i].split("=");
		if(ss[0]==name && ss.length>1){
			return ss[1];
		}
	}
	return null;
	
}

/**
 * 初始化必选lable
 */
function initMustLable(){
	$('.mustLabel').each(function(){
		var icon = '<font color="red">*</font>';
		$(this).append(icon);
	});
}

/**
 * 空处理
 * @param str
 * @returns {String}
 */
function handNull(str){
	var retStr = str;
	if(typeof str == "undefined" || str == "null" || str == "NULL" || str == null){
		retStr = "";
	}
	return retStr;
}

/**
 * 按钮权限控制
 * @param json
 */
function qryBtnQriv(json){
	var obj = eval("("+json+")");
	var hasBtn = new Array();
	if(""!=obj&&null!=obj){
		$(".qrivBtns > button").each(function(){
			var id = $(this).attr("id");
			if(null!=obj[id]){
				if(obj[id] == "false"){
					$(this).remove();
				}	
			} else {
				hasBtn.push(id);
			}
			
		});
		//特殊处理
		if(obj["btn"] == "false"){
			$(".qrivBtns > button").each(function(){
				var id = $(this).attr("id");
				for(var i=0;i<hasBtn.length;i++){
					if(id == hasBtn[i]){
						$(this).remove();
					}
				}
			});
		}
	}
}

/**
 * 获得字符串实际长度，中文2，英文1
 */
getBLen = function(str) {
	var realLength = 0, len = str.length, charCode = -1;  
    for (var i = 0; i < len; i++) {  
        charCode = str.charCodeAt(i);  
        if (charCode >= 0 && charCode <= 128) realLength += 1;  
        else realLength += 2;  
    }  
    return realLength;
}